package main.com.oaer.dao.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import main.com.oaer.common.HibernateDaoUtil;
import main.com.oaer.dao.PurviewDao;
import main.com.oaer.model.Purview;

@Repository
public class PurviewDaoImpl implements PurviewDao{
    
	@Autowired
	private  HibernateDaoUtil hibernateDaoUtil;
	
	@Override
	public void add(Purview purview) {
		hibernateDaoUtil.save(purview);
	}

	@Override
	public List<Map<String, Object>> findPurviews() {
		String hql = "select" +
				" purview.id as id, " +
				" purview.url as url, " +
				" purview.parentId as pId," +
				" purview.level as level," +
				" purview.name as name " +
				" from Purview  purview";		
		return hibernateDaoUtil.findListMapByHQL(hql, null);
	}

	@Override
	public void delete(Purview purview) {
		if(purview!=null){
			hibernateDaoUtil.delete(purview);
		}
	}

	@Override
	public void update(Purview purview) {
		if(purview != null){
			Purview tempPurview = hibernateDaoUtil.load(Purview.class, purview.getId());
			tempPurview.setLevel(purview.getLevel());
			tempPurview.setName(purview.getName());
			tempPurview.setUrl(purview.getUrl());
		}
	}


	@Override
	public List<Purview> findChildPurview(Long id) {
		if(id==null) return null;
		String hql = " from Purview purview " +
				" where " +
				" purview.parentId=?";
		return hibernateDaoUtil.findListByHQL(hql, id);
	}

	@Override
	public Purview getPurview(String url) {
		if(url==null) return null;
		String hql = " from " +
				" Purview purview " +
                " where " +
                " purview.url=?";
		return (Purview) hibernateDaoUtil.findEntityByHQL(hql, url);
	}

	@Override
	public List<Purview> findSiblingPurview(Long parentId, Long userId) {
		if(parentId==null || userId==null) return null;
		String hql = "select purview from " +
				" Purview purview," +
				" RolePurview rolePurview," +
				" UserRole userRole " +
				" where " +
				" userRole.userId=? " +
				" and " +
				" userRole.roleId=rolePurview.roleId " +
				" and " +
				" rolePurview.purviewId=purview.id " +
				" and " +
				" purview.parentId=?";
		return hibernateDaoUtil.findListByHQL(hql, userId, parentId);
	}

	@Override
	public Purview load(Long id) {
		if(id==null) return null;
		return hibernateDaoUtil.get(Purview.class, id);
	}

}
